/** 当前激活的流程列表 */
import {Component, createRef} from "react";
import {Col, Form, Row, Space, Table, Tag, DatePicker, Button, FormInstance, AutoComplete, Divider, Select, Popover} from "antd";

import TaskDetail from "../../../components/Tools/Detail/Task";
import InstanceDetail from "../../../components/Tools/Detail/Instance";

import {ColumnsType, TablePaginationConfig} from "antd/es/table";

import {URL, send} from '../../../utils/http.util.tsx'
import {randomString, fmtDate, PageUtil, DEFAULT_PAGINATION, Handler} from '../../../utils/util.tsx'

// @ts-ignore
import './index.css'
import LazyIcon from "../../../components/Tools/Icon";
import {Typography} from 'antd';
import {Data, State, Props, Node} from './types.tsx'

const {Link} = Typography;
const {RangePicker} = DatePicker;

class Current extends Component<Props, State> {
    taskDetailRef = createRef<TaskDetail>()
    instanceDetailRef = createRef<InstanceDetail>()

    formRef = createRef<FormInstance>()

    nodes: Node[] = []
    /** 表格的列定义 */
    columns: ColumnsType<Data> = [
        {
            title: '问卷 ID',
            dataIndex: 'instanceId',
            key: 'instanceId',
            render: (_, record) => (
                <Space size="middle">
                    <Link onClick={() => this.showInstanceDetail(record)}>{record.instanceId}</Link>
                </Space>
            )
        },
        {
            title: '节点',
            dataIndex: 'taskName',
            key: 'taskName',
            render: (text, record) => (
                <Popover placement="top" content={"节点 ID：" + record.id}>
                    <Tag color='geekblue' key={text}>
                        {text}
                    </Tag>
                </Popover>
            )
        },
        {
            title: '发起人',
            dataIndex: 'instanceCreateBy',
            key: 'instanceCreateBy',
        },
        {
            title: '审核人',
            dataIndex: 'actors',
            key: 'actors',
            render: (_, record) => {
                const actorIds = record.actorIds.split(',')
                const actorNames = record.actorNames.split(',')
                const actorNum = actorIds.length

                return actorIds.map((_actorId, idx) => {
                    if (idx != actorNum - 1) {
                        return (
                            <>
                                {actorNames[idx]}
                                <Divider type={"vertical"}/>
                            </>
                        )
                    }
                    return actorNames[idx]
                })
            }
        },
        {
            title: '发起时间',
            dataIndex: 'instanceCreateTime',
            key: 'instanceCreateTime',
            render: text => <>{fmtDate(text)}</>
        },
        {
            title: '更新时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: text => <>{fmtDate(text)}</>
        },
        {
            title: '操作',
            dataIndex: 'ops',
            key: 'ops',
            render: (_, record) => (
                <Space size="middle">
                    <Link onClick={() => this.handleProcess(record)}>审核</Link>
                </Space>
            )
        }
    ]

    state = {
        data: [],
        pagination: DEFAULT_PAGINATION,
        loading: true,

        optionsOfCreateBy: [], // CreateBy AutoComplete 组件的 options
        createId: undefined,
    }

    componentDidMount() {
        if (this.props.embedded) {
            return
        }

        this.handleFetch();

        send(URL.nodes).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.nodes = data.map((item: { nodeKey: string, nodeName: string }) => {
                    return {value: item.nodeName, label: item.nodeName, key: randomString()}
                })
                this.nodes = [{value: null, label: '全部', key: randomString()}, ...this.nodes]
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    refresh(createId: string) {
        this.setState({createId}, () => this.handleFetch())
    }

    handleFetch(qo: any = undefined, pagination: TablePaginationConfig | undefined = undefined) {
        this.setState({loading: true})
        if (qo) {
            if (qo.createTimeArr) {
                qo.createTimeStart = qo.createTimeArr[0].valueOf()
                qo.createTimeEnd = qo.createTimeArr[1].valueOf()
                delete qo.createTimeArr;
            }
        } else {
            qo = {}
        }

        if (this.state.createId) {
            qo.createId = this.state.createId
        }

        send(URL.currentInstance, {...qo, ...PageUtil.toDto(pagination)}).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.setState(
                    {
                        data: data.records.map((item: { key: number, id: number }) => {
                                return {
                                    ...item,
                                    key: randomString()
                                }
                            }
                        ),
                        pagination: PageUtil.toPagination(data),
                        loading: false
                    }
                );
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    handleFetchNicknameLike(keyword: string) {
        send(URL.userNicknamesAutoComplete, {nickNameLike: keyword}).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.setState({optionsOfCreateBy: data})
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    /**
     * Description: 显示任务详情并审批 (通过或驳回).
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-05-11 10:26:23
     */
    handleProcess(task: Data) {
        this.setState({loading: !this.state.loading})

        const taskId = task.id
        send(URL.taskDetail, null, [taskId]).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.taskDetailRef.current?.showTaskDetail(data) // - 显示任务详情
                this.setState({loading: !this.state.loading})
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    /**
     * Description: 查看流程详情.
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-05-11 10:27:46
     */
    showInstanceDetail(task: Data) {
        this.setState({loading: !this.state.loading})

        const instanceId = task.instanceId;
        send(URL.instanceDetail, null, [instanceId]).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.instanceDetailRef.current?.showInstanceDetail(data)
                this.setState({loading: !this.state.loading})
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    render() {
        const {data, pagination, loading} = this.state;

        const embedded: boolean = this.props.embedded;
        return (
            <>
                <Form ref={this.formRef} onFinish={(qo) => this.handleFetch(qo)} className="queryForm">
                    <Row gutter={24}>
                        {!embedded &&
                            (
                                <Col span={8}>
                                    <Form.Item label="发起人" name="instanceCreateByLike">
                                        <AutoComplete onSearch={(keyword) => this.handleFetchNicknameLike(keyword)} options={this.state.optionsOfCreateBy} placeholder="请输入关键字"/>
                                    </Form.Item>
                                </Col>
                            )
                        }
                        <Col span={8}>
                            <Form.Item label="更新时间" name="createTimeArr">
                                <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder={['开始时间', '结束时间']}/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="节点" name="taskName">
                                <Select options={this.nodes} defaultValue={null}/>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={24}>
                            <Space size={"middle"} style={{float: "right"}}>
                                <Button icon={<LazyIcon iconName="ClearOutlined"/>} htmlType="button" onClick={() => this.formRef.current?.resetFields()}>重置</Button>
                                <Button icon={<LazyIcon iconName="SearchOutlined"/>} type="primary" htmlType="submit">查询</Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>
                <Table
                    footer={() => `总共 ${this.state.pagination.total} 条数据`} loading={loading}
                    columns={
                        this.columns.filter(
                            (column) => {
                                if (!embedded) {
                                    return column
                                }
                                return column.key != 'instanceCreateBy'
                            }
                        )
                    }
                    pagination={pagination} dataSource={data} onChange={(pagination) => this.handleFetch(undefined, pagination)}></Table>

                <TaskDetail ref={this.taskDetailRef}></TaskDetail>
                <InstanceDetail ref={this.instanceDetailRef}></InstanceDetail>
            </>
        )
    }
}

export default Current;
